'use strict';

const BaseController = require('./base');
const { addRules, editRules, findRules, deleteRules } = require('../validator/category/index');
class CategoryController extends BaseController {

  /**
   * 广场推荐话题分类
   */
  async recommend() {
    const categories = await this.service.category.findByRecommend();
    this.ctx.helper.success({beans: categories});
  }

  // 新增话题分类
  async add() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(addRules, ctx.request.body);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const data = ctx.request.body;
    const res = await service.category.add(data);
    ctx.helper.success({ bean: res }, '新增话题分类成功');
  }

  // 编辑话题分类
  async edit() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(editRules, ctx.request.body);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const data = ctx.request.body;
    const id = data.id;
    delete data.id;
    await service.category.edit(id, {
      ...data,
      update_time: ctx.helper.time(),
    });
    ctx.helper.success({}, '编辑话题分类成功');
  }

  // 查询话题
  async query() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(findRules, ctx.request.query);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const data = ctx.request.query;
    const res = await service.category.query(data.id);
    if (Object.prototype.toString.call(res) === '[object Array]') {
      ctx.helper.success({ beans: res }, '查询话题分类成功');
    } else {
      ctx.helper.success({ bean: res }, '查询话题分类详情成功');
    }
  }

  // 查询用户发过的话题
  async queryUserPublish() {
    const { ctx, service, app } = this;
    const id = ctx.helper.decodeJwt(ctx);
    const res = await service.category.queryUserPublish(id);
    ctx.helper.success({ beans: res }, '查询话题分类成功');
  }


  // 删除话题
  async delete() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(deleteRules, ctx.request.body);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const { id } = ctx.request.body;
    await service.category.delete(id, ctx.helper.time());
    ctx.helper.success({}, '删除话题分类成功');
  }
}

module.exports = CategoryController;
